package com.example.parking.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.parking.common.Result;
import com.example.parking.entity.User;
import com.example.parking.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 用户注册
    @PostMapping("/register")
    public Result<?> register(@RequestBody User user) {
        if (user == null || user.getUsername() == null || user.getPassword() == null) {
            return Result.error("用户名和密码不能为空");
        }
        if (userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername())) != null) {
            return Result.error("用户名已存在");
        }
        // 密码加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        user.setStatus(1);
        user.setRole(1);
        userService.save(user);
        return Result.success();
    }

    // 用户登录
    @PostMapping("/login")
    public Result<?> login(@RequestBody User user, HttpSession session) {
        if (user == null || user.getUsername() == null || user.getPassword() == null) {
            return Result.error("用户名和密码不能为空");
        }
        User dbUser = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername()));
        if (dbUser == null) {
            return Result.error("用户不存在");
        }
        String pwd = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        if (!dbUser.getPassword().equals(pwd)) {
            return Result.error("密码错误");
        }
        if (dbUser.getStatus() == 0) {
            return Result.error("账号已禁用");
        }
        session.setAttribute("user", dbUser);
        return Result.success(dbUser);
    }

    // 用户登出
    @PostMapping("/logout")
    public Result<?> logout(HttpSession session) {
        session.removeAttribute("user");
        return Result.success();
    }

    // 查询所有用户（用于下拉框）
    @GetMapping("/list")
    public Result<?> listAll() {
        return Result.success(userService.list());
    }

    // 用户分页查询
    @GetMapping("/page")
    public Result<IPage<User>> findPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String username) {

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (username != null && !username.isEmpty()) {
            queryWrapper.like(User::getUsername, username);
        }

        IPage<User> page = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }

    // 新增用户
    @PostMapping
    public Result<?> add(@RequestBody User user) {
        if (user == null || user.getUsername() == null || user.getPassword() == null) {
            return Result.error("用户名和密码不能为空");
        }
        if (userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername())) != null) {
            return Result.error("用户名已存在");
        }
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        userService.save(user);
        return Result.success();
    }

    // 更新用户
    @PutMapping("/{id}")
    public Result<?> update(@PathVariable Integer id, @RequestBody User user) {
        User existingUser = userService.getById(id);
        if (existingUser == null) {
            return Result.error("用户不存在");
        }
        // 复制非空属性，但不包括密码（如果前端未提供新密码，则不更新密码）
        BeanUtils.copyProperties(user, existingUser, "id", "password");

        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            existingUser.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        }
        userService.updateById(existingUser);
        return Result.success();
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Integer id) {
        userService.removeById(id);
        return Result.success();
    }

    // 根据ID查询用户
    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Integer id) {
        User user = userService.getById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }
        return Result.success(user);
    }
} 